package com.srs.dao.agent;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.srs.model.agent.Agent;
import com.srs.util.HibernateUtil;

public class AgentDao {

	final static Logger logger = LoggerFactory.getLogger(AgentDao.class);

	private List<Agent> agentList;
	private Agent agent;

	public void delete(Integer agentId) {

		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			agent = (Agent) session.get(Agent.class, agentId);
			session.delete(agent);
			tx.commit();

		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Agent> list() {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			agentList = session.createQuery("from Agent").list();
			return agentList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}

	@SuppressWarnings("unchecked")
	public List<Agent> list(Integer cellId, String msisdn, String customerId, String imei) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			String query = "from Agent a where 1=1 ";
			if (cellId!=null && cellId!=0){
				query = query + " and a.cellId=" + cellId;
			}
			if (msisdn!=null && !"".equalsIgnoreCase(msisdn)){
				query = query + " and a.msisdn like '%" + msisdn + "%'";
			}
			if (customerId!=null && !"".equalsIgnoreCase(customerId)){
				query = query + " and a.customerId like '%" + customerId + "%'";
			}
			if (imei!=null && !"".equalsIgnoreCase(imei)){
				query = query + " and a.imei like '%" + imei + "%'";
			}			
			agentList = session.createQuery(query).list();
			return agentList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}
	
	@SuppressWarnings("unchecked")
	public List<Agent> list(Integer countryId, Integer areaId, Integer provinceId, Integer cellId, String msisdn, String customerId, String imei) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			String query = "from Agent a where 1=1 ";
			if (countryId!=null && countryId!=0){
				query = query + " and a.countryId=" + countryId;
			}
			if (areaId!=null && areaId!=0){
				query = query + " and a.areaId=" + areaId;
			}
			if (provinceId!=null&&provinceId!=0){
				query = query + " and a.provinceId=" + provinceId;
			}
			if (cellId!=null && cellId!=0){
				query = query + " and a.cellId=" + cellId;
			}	
			if (msisdn!=null && !"".equalsIgnoreCase(msisdn)){
				query = query + " and a.msisdn like '%" + msisdn + "%'";
			}
			if (customerId!=null && !"".equalsIgnoreCase(customerId)){
				query = query + " and a.customerId like '%" + customerId + "%'";
			}
			if (imei!=null && !"".equalsIgnoreCase(imei)){
				query = query + " and a.imei like '%" + imei + "%'";
			}			
			agentList = session.createQuery(query).list();
			return agentList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}		
	
	@SuppressWarnings("unchecked")
	public List<Agent> list(Integer countryId, Integer areaId, Integer provinceId, Integer cellId) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			String query = "from Agent a where 1=1 ";
			if (countryId!=null && countryId!=0){
				query = query + " and a.countryId=:countryId";
			}
			if (areaId!=null && areaId!=0){
				query = query + " and a.areaId=:areaId";
			}
			if (provinceId!=null&&provinceId!=0){
				query = query + " and a.provinceId=:provinceId";
			}
			if (cellId!=null&&cellId!=0){
				query = query + " and a.cellId=:cellId";
			}			
			agentList = session.createQuery(query).list();
			return agentList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}		
	
	@SuppressWarnings("unchecked")
	public String listForCondition(Integer countryId, Integer areaId, Integer provinceId, Integer cellId) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			String query = "from Agent a where 1=1 ";
			if (countryId!=null && countryId!=0){
				query = query + " and a.countryId=" + countryId;
			}
			if (areaId!=null && areaId!=0){
				query = query + " and a.areaId=" + areaId;
			}
			if (provinceId!=null&&provinceId!=0){
				query = query + " and a.provinceId=" + provinceId;
			}
			if (cellId!=null&&cellId!=0){
				query = query + " and a.cellId=" + cellId;
			}			
			agentList = session.createQuery(query).list();
			
			String result = "(";
			
			for (Agent item : agentList) {
				result = result + item.getAgentId() + ", ";
			}
			result = result.substring(0, result.length()-2) + ')';
			return result;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return "(0)";
		} finally {
			session.close();
		}

	}			
	
	@SuppressWarnings("unchecked")
	public List<Agent> listAgentForCellId() {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			agentList = session.createQuery("from Agent").list();

			for(int i=0; i<agentList.size(); i++){
				for(int j=agentList.size()-1; j>i; j--){
					try {
						if (agentList.get(j).getCellId()==null){
							agentList.remove(j);
						}else if (agentList.get(i).getCellId().intValue()==agentList.get(j).getCellId().intValue()){
							agentList.remove(j);
						}					
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}			
			
			return agentList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}	
	
	@SuppressWarnings("unchecked")
	public List<Agent> listAgentForCellId(Integer provinceId) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			Query q = session.createQuery("select a.cellId from Agent a where a.provinceId=:provinceId");
			q.setInteger("provinceId", provinceId);
			agentList = q.list();
			for(int i=0; i<agentList.size(); i++){
				for(int j=agentList.size()-1; j>i; j--){
					try {
						if (agentList.get(j).getCellId()==null){
							agentList.remove(j);
						}else if (agentList.get(i).getCellId().intValue()==agentList.get(j).getCellId().intValue()){
							agentList.remove(j);
						}					
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}		

			return agentList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}	
	
	@SuppressWarnings("unchecked")
	public List<Agent> listAlert(List<Integer> agentIds) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			for(int i=0; i<agentIds.size(); i++){
				for(int j=agentIds.size()-1; j>i; j--){
					try {
						if (agentIds.get(j)==null){
							agentIds.remove(j);
						}else if (agentIds.get(i).intValue()==agentIds.get(j).intValue()){
							agentIds.remove(j);
						}					
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
			
			String inCondition = " in (" + agentIds.get(0).toString();
			for (int i=1; i<agentIds.size(); i++) {
				inCondition = inCondition + ", " + agentIds.get(i).toString() ;
			}
			inCondition = inCondition + ")";
			
			agentList = session.createQuery("from Agent a where a.agentId " + inCondition).list();
			return agentList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}
	
	@SuppressWarnings("unchecked")
	public List<Agent> listAlert(List<Integer> agentIds, Integer cellId) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			for(int i=0; i<agentIds.size(); i++){
				for(int j=agentIds.size()-1; j>i; j--){
					try {
						if (agentIds.get(j)==null){
							agentIds.remove(j);
						}else if (agentIds.get(i).intValue()==agentIds.get(j).intValue()){
							agentIds.remove(j);
						}					
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
			
			String inCondition = " in (" + agentIds.get(0).toString();
			for (int i=1; i<agentIds.size(); i++) {
				inCondition = inCondition + ", " + agentIds.get(i).toString() ;
			}
			inCondition = inCondition + ")";
			
			agentList = session.createQuery("from Agent a where a.agentId " + inCondition + " and a.cellId=" + cellId).list();
			return agentList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}	
	
	@SuppressWarnings("unchecked")
	public List<Agent> listAlert(List<Integer> agentIds, String agents) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			for(int i=0; i<agentIds.size(); i++){
				for(int j=agentIds.size()-1; j>i; j--){
					try {
						if (agentIds.get(j)==null){
							agentIds.remove(j);
						}else if (agentIds.get(i).intValue()==agentIds.get(j).intValue()){
							agentIds.remove(j);
						}					
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
			
			String inCondition = " in (" + agentIds.get(0).toString();
			for (int i=1; i<agentIds.size(); i++) {
				inCondition = inCondition + ", " + agentIds.get(i).toString() ;
			}
			inCondition = inCondition + ")";
			
			agentList = session.createQuery("from Agent a where a.agentId " + inCondition + " and a.agentId in " + agents).list();
			return agentList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}		
	
	public Boolean nameIsUsed(String msisdn) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			// change query for get proper data
			Query q = session.createQuery("from Agent a where a.msisdn=:msisdn");
			q.setString("msisdn", msisdn);
			agentList = q.list();
			if (agentList.size()==0) {
				return false;
			}
			return true;
		} finally {
			session.close();
		}

	}	
	
	public Agent get(Integer agentId) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			// change query for get proper data
			Query q = session
					.createQuery("from Agent a where a.agentId=:agentId");
			q.setInteger("agentId", agentId);
			return (Agent) q.uniqueResult();
		} finally {
			session.close();
		}

	}

	public void insert(Agent agent) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(agent);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

	}

	public void update(Agent agent) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(agent);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

	}

	public static void main(String[] args) {
		// Init sessionFactory
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		HibernateUtil.setSessionFactory(sessionFactory);
		
		// Get list params
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		
		Query q = session.createQuery("select a.cellId from Agent a where a.provinceId=:provinceId");
		q.setInteger("provinceId", 15);
		List<Integer> cells = q.list();
		for(int i=0; i<cells.size(); i++){
			for(int j=cells.size()-1; j>i; j--){
				try {
					if (cells.get(j)==null){
						cells.remove(j);
					}else if (cells.get(i).intValue()==cells.get(j).intValue()){
						cells.remove(j);
					}					
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		String inCondition = " in (" + cells.get(0).toString();
		for (int i=1; i<cells.size(); i++) {
			inCondition = inCondition + ", " + cells.get(i).toString() ;
		}
		inCondition = inCondition + ")";
		
		List<Agent> agentList = session.createQuery("from Agent a where a.cellId " + inCondition).list();
		System.out.println(agentList);
	} 
}
